package com.ocm.controller.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.ocm.core.dto.ClassDefinitionDto;
import com.ocm.core.service.ClassDefService;

@Component("classDefValidator")
public class ClassDefValidator implements Validator {

   private ClassDefService classDefService;

   @Autowired
   public ClassDefValidator(@Qualifier("classDefService") ClassDefService classDefService) {
      this.classDefService = classDefService;
   }

   public boolean supports(Class<?> classDef) {
      return ClassDefinitionDto.class.isAssignableFrom(classDef);
   }

   public void validate(Object object, Errors errors) {
      validateClassDef(object, errors);
   }

   public void validateClassDef(long storageId, Object object, Errors errors) {
      ClassDefinitionDto classDefinitionDto = (ClassDefinitionDto) object;
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "displayName", "err.required");
      if (!errors.hasFieldErrors("name")) {
         if (StringUtils.containsWhitespace(classDefinitionDto.getName())) {
            errors.rejectValue("name", "err.containsWhitespace");
         }
      }

      if (!errors.hasFieldErrors("name") && (classDefinitionDto.getId() == null || classDefinitionDto.getId() == 0)) {
         boolean existedName = classDefService.hasExistName(storageId,classDefinitionDto.getName());
         if (existedName)
            errors.rejectValue("name", "err.unique");
      }
   }

   public void validateClassDef(Object object, Errors errors) {
      ClassDefinitionDto classDefinitionDto = (ClassDefinitionDto) object;
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "displayName", "err.required");
      if (!errors.hasFieldErrors("name")) {
         if (StringUtils.containsWhitespace(classDefinitionDto.getName())) {
            errors.rejectValue("name", "err.containsWhitespace");
         }
      }
   }
}
